<template>
    <div class="container_box">
        <div class="main_box">
            <div class="content">
                <el-scrollbar class="scrollbar_left">
                    <div class="content-left">
                        <div class="list_item">
                            <div class="item_title"><span class="title_icon"></span>适用员工选择</div>
                            <div class="item_con">
                                <el-radio-group v-model="form.is_staff" class="radio_group" @change="changeStaff">
                                    <el-radio :label="1">全部员工</el-radio>
                                    <el-radio :label="0">指定员工</el-radio>
                                </el-radio-group>
                                <el-select
                                    v-if="form.is_staff == 0"
                                    ref="selectRef"
                                    v-model="form.user_id"
                                    popper-class="hide_select_option"
                                    :popper-append-to-body="false"
                                    class="form_item_input"
                                    multiple
                                    placeholder="全部"
                                    @click="openDepart"
                                    @change="changeDepart">
                                    <el-option
                                        v-for="item in creators"
                                        :key="item?.id"
                                        :label="item?.name"
                                        :value="item?.id"
                                        >{{ item?.name }}</el-option
                                    >
                                </el-select>
                            </div>
                        </div>
                        <div class="list_item mt20">
                            <div class="item_title"><span class="title_icon"></span>欢迎语内容配置</div>
                            <MaterialContent
                                ref="materialContentRef"
                                :max-num="9"
                                :input-content-tabs="inputContentTabs"
                                :show-material-tabs="showMaterialTabs"
                                :input-content-data="inputContentData"
                                :material-content-data="materialContentData"
                                @change="changeMaterial" />
                        </div>
                    </div>
                </el-scrollbar>
                <el-scrollbar>
                    <div class="content-right">
                        <div class="title">欢迎语预览</div>
                        <PhonePreview ref="phonePreviewRef" />
                    </div>
                </el-scrollbar>
            </div>
            <!-- 部门人员弹框 -->
            <ZWDepart ref="DepartRef" @submit="getDepart" />
            <!--  -->
            <UpdateWelcome ref="updateWelcomeRef" @submit="onUpdateWelcome" />
        </div>
        <div class="footer_box">
            <el-button @click="resetForm">重置</el-button>
            <el-button type="primary" @click="noticeSend">保存</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import ZWDepart from '@/components/ZWDepart.vue';

import MaterialContent from '@/components/zw/materialContent/index.vue';
import PhonePreview from '@/components/zw/phonePreview/welcomePhonePreview/materialPreview/index.vue';
import UpdateWelcome from '../../components/UpdateWelcome.vue';

import { channelCreateFriend, channelFriendInfo, channelFriendUpdate, welcomeFriendList } from '@/api/channel/qwbase';
import { getSetionId, initMaterialData, getContentHeight } from '@/utils/utils';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const materialContentRef = ref<HTMLElement | null>();
const phonePreviewRef = ref<HTMLElement | null>();
const inputContentTabs = ref<Array<number>>([1, 2, 4]); // 配置欢迎语输入框选项
const showMaterialTabs = ref<Array<string>>(['1', '2', '3', '4', '5', '7', '9', '11', '10']); // 配置选择素材组件类型
const inputContentData = ref<string>(''); //  用户存放回显数据  欢迎语输入框
const materialContentData = ref<Array<any>>([]); //  用户存放回显数据  欢迎语素材
const disabled = ref<boolean>(true);

const DepartRef = ref(null);
const selectRef: any = ref(null);
const cust_filter_json = ref({
    work_user: [],
    work_department: []
});
const newArr = ref([]);
const creators = ref([]);
const uId = ref();
const fileList2 = ref([]);
const materialResult = ref<any>(null);

const updateWelcomeRef = ref<any>(null);

const form = reactive({
    is_staff: 1, //1全部员工 0 指定员工
    user_id: [],
    content: ''
});
const fileList = ref([]);
//切换员工选择
const changeStaff = () => {
    if (form.is_staff == 0) {
        form.user_id = [];
    }
};
// 重置
const resetForm = () => {
    form.is_staff = 1; //1全部员工 0 指定员工
    form.user_id = [];
    form.content = '';
    fileList.value = [];
    fileList2.value = [];
    cust_filter_json.value.work_user = [];
    cust_filter_json.value.work_department = [];
    // inputContentData.value = ''
    // materialContentData.value = []
    materialContentRef.value.clearInput();
    materialContentRef.value.clearMaterial();
};

const changeMaterial = (val: any) => {
    materialResult.value = val;
};

const noticeSend = async () => {
    const params2 = {
        ...materialResult.value,
        is_staff: form.is_staff,
        work_user_ids: cust_filter_json.value.work_user,
        work_department_ids: cust_filter_json.value.work_department
    };
    if (uId.value) {
        const data = {
            welcome_friend_id: uId.value,
            is_modify: 0,
            activity_type: 0,
            activity_name: '',
            created_uid: '',
            created_at: [],
            page: 1,
            page_size: 15
        };
        const res = await welcomeFriendList(data);
        if (res.data?.length) {
            updateWelcomeRef.value.state.searchParams.welcome_friend_id = '';
            updateWelcomeRef.value.state.searchParams.welcome_friend_id = uId.value;
            updateWelcomeRef.value.appDialog.visible = true;
            return;
        }
        onWelcomeFriendEdit();
        // params2['welcome_friend_id'] = Number(uId.value)
        // channelFriendUpdate(params2).then((res: any) => {
        //   ElMessage.success(`编辑成功`)
        //   router.back()
        // })
    } else {
        channelCreateFriend(params2).then((res: any) => {
            ElMessage.success(`创建成功`);
            router.back();
        });
    }
};
//打开新建选择人
const openDepart = () => {
    selectRef.value.blur();
    DepartRef.value.appDialog.title = '选择部门/员工';
    DepartRef.value.departVisble = true;
    DepartRef.value.isMember = false; // 可以选择部门
    DepartRef.value.selectedMember = creators.value;
};
// 获取部门成员
const getDepart = (res: any) => {
    cust_filter_json.value.work_user = [];
    cust_filter_json.value.work_department = [];
    creators.value = res;
    form.user_id = getSetionId('id', res);
    res.forEach((item: any) => {
        if (item.type == 'department') {
            cust_filter_json.value.work_department.push(item.id);
        } else {
            cust_filter_json.value.work_user.push(item.id);
        }
    });
};
// 删除部门成员
const changeDepart = (data: any) => {
    const removeDepart = creators.value.find((item: any) => !data.includes(item.id));
    const arr: any[] = creators.value.filter((item: any) => data.includes(item.id));
    form.user_id = getSetionId('id', arr);
    creators.value = arr;
    // DepartRef.value.NaNpxoveItem(removeDepart)
    cust_filter_json.value = {
        work_user: [],
        work_department: []
    };
    // 添加员工
    if (creators.value.length > 0) {
        creators.value.forEach((item: any) => {
            //部门
            if (item.type == 'department') {
                cust_filter_json.value.work_department.push(item.id);
            } else {
                // 成员
                cust_filter_json.value.work_user.push(item.id);
            }
        });
    }
};

const contentHeight = computed(() => getContentHeight());

const onUpdateWelcome = (type: number, ids: any, isAsync?: any, e?: any) => {
    const params = {
        market_filter: {
            ...updateWelcomeRef.value.state.searchParams,
            select_type: type,
            activity_ids: ids
        }
    };
    onWelcomeFriendEdit(params, isAsync, e);
};
const onWelcomeFriendEdit = async (data: any = {}, isAsync?: any, e) => {
    const params = {
        ...materialResult.value,
        is_staff: form.is_staff,
        work_user_ids: cust_filter_json.value.work_user,
        work_department_ids: cust_filter_json.value.work_department,
        ...data
    };
    params['welcome_friend_id'] = Number(uId.value);
    const res = await channelFriendUpdate(params);
    if (res) {
        ElMessage.success(`编辑成功`);
        if (isAsync) {
            parabolaAnimation(e);
            ShowTaskMessage('批量更新欢迎语异步任务创建成功');
        }
        router.back();
    }
};

onMounted(async () => {
    uId.value = router.currentRoute.value.query.uid;
    if (!uId.value) return;
    try {
        const res: any = await channelFriendInfo({
            welcome_friend_id: uId.value
        });
        form.is_staff = res.is_staff; //1全部员工 0 指定员工
        inputContentData.value = res.welcome_info.welcome_text;
        materialContentData.value = initMaterialData(res.welcome_info.welcome_material);
        if (res.department.length > 0) {
            res.department.map((item: any) => (item.type = 'department'));
            creators.value = res.department;
            form.user_id = getSetionId('id', res.department);
            cust_filter_json.value.work_department = getSetionId('id', res.department);
        }
        if (res.work_user.length > 0) {
            creators.value = creators.value.concat(res.work_user);
            form.user_id = form.user_id.concat(getSetionId('id', res.work_user));
            cust_filter_json.value.work_user = getSetionId('id', res.work_user);
        }
        newArr.value = fileList.value.filter((item: any) => item.type != 0);
    } catch (e) {}
});
</script>
<style lang="scss" src="./style.scss" scoped></style>
